package com.huaxiafinance.management.controller;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huaxiafinance.management.dto.request.CaptchaDto;
import com.huaxiafinance.management.dto.request.LoginDto;
import com.huaxiafinance.management.dto.request.QueryRoleDto;
import com.huaxiafinance.management.dto.request.UpdateUserPasswordDto;
import com.huaxiafinance.management.model.Role;
import com.huaxiafinance.management.model.User;
import com.huaxiafinance.management.model.UserRole;
import com.huaxiafinance.management.service.UserService;
import com.huaxiafinance.management.util.CaptchaUtil;
import com.huaxiafinance.management.util.DesUtil;
import com.huaxiafinance.management.util.MessageResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

@Controller("adminUserController")
@RequestMapping("/adminUser")
public class AdminUserController {

    private static final Logger log = Logger.getLogger(AdminUserController.class);

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", produces = "application/json; charset=utf-8")
    public @ResponseBody
    String login(@Valid @ModelAttribute("loginDto") LoginDto dto, final HttpSession seesion,
                 HttpServletResponse response) throws Exception {
        log.info("用户登录请求参数====================>" + dto);

        MessageResult messageResult = userService.login(dto, seesion, response);

        ObjectMapper mapper = new ObjectMapper();
        String json = "success_jsonpCallback(" + mapper.writeValueAsString(messageResult) + ")";


        log.info("用户登录返回参数" + json);
        return json;
    }

    /**
     * 获取验证码
     *
     * @param response
     * @param request
     * @param dto
     */
    @RequestMapping(value = "/getCaptcha")
    public void getCaptcha(final HttpServletResponse response, final HttpServletRequest request,
                           @Valid @ModelAttribute("dto") CaptchaDto dto) {

        CaptchaUtil.getCaptcha(request.getSession(), response, dto);
    }

    @RequestMapping(value = "/updatePassword")
    public @ResponseBody
    String updatePassword(@Valid @ModelAttribute("dto") UpdateUserPasswordDto dto)
            throws Exception {
        log.info("用户修改密码请求参数" + dto);

        MessageResult messageResult = new MessageResult();

        boolean flag = userService.updatePassword(dto);

        if (flag)
            messageResult.setSuccessResult();
        else
            messageResult.setFailureResult();

        log.info("用户修改密码返回参数" + messageResult.getAsJSON());
        return messageResult.getAsJSON();
    }

    @RequestMapping(value = "/addUser", produces = "application/json; charset=utf-8")
    public @ResponseBody
    String addUser(HttpServletRequest request, String orgCode) throws Exception {
        String json = request.getParameter("json");
        String state = request.getParameter("state");
        String regionCode = request.getParameter("regionCode");
        String provCode = request.getParameter("provCode");
        String saleCode = request.getParameter("saleCode");


        log.info("新增用户请求参数" + json);

        MessageResult messageResult = new MessageResult();

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        User user = mapper.readValue(json, User.class);

        if (user.getCellphone() != null && !("").equals(user.getCellphone())) {
            if (!user.getCellphone().matches("^1[3,4,5,6,7,8,9]\\d{9}$")) {
                messageResult.setFailureResult("请输入正确电话号码");
                return messageResult.getAsJSON();
            }
        }

        user.setState(Integer.parseInt(state));
        user.setRegionCode(regionCode);
        user.setProvCode(provCode);
        user.setSaleCode(saleCode);
        //密码加密
        DesUtil.entryptPassword(user);

        messageResult = userService.addUser(user);

        log.info("新增用户返回参数" + messageResult.getAsJSON());

        return messageResult.getAsJSON();
    }

    @RequestMapping(value = "/delUser", produces = "application/json; charset=utf-8")
    public @ResponseBody
    String delUser(Integer id) throws Exception {
        log.info("删除用户请求参数" + id);

        MessageResult messageResult = new MessageResult();

        boolean flag = userService.delUser(id);

        if (flag)
            messageResult.setSuccessResult();
        else
            messageResult.setFailureResult();

        log.info("删除用户返回参数" + messageResult.getAsJSON());

        return messageResult.getAsJSON();
    }

    @RequestMapping(value = "/updUser", produces = "application/json; charset=utf-8")
    public @ResponseBody
    String updUser(HttpServletRequest request) throws Exception {
        String json = request.getParameter("json");

        log.info("修改用户请求参数" + json);

        MessageResult messageResult = new MessageResult();

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        User user = mapper.readValue(json, User.class);
        if (user.getCellphone() != null && !("").equals(user.getCellphone())) {
            if (!user.getCellphone().matches("^1[3,4,5,6,7,8,9]\\d{9}$")) {
                messageResult.setFailureResult("请输入正确电话号码");
                return messageResult.getAsJSON();
            }
        }

        boolean flag = userService.updUser(user);

        if (flag)
            messageResult.setSuccessResult();
        else
            messageResult.setFailureResult("手机号和用户名不能重复");

        log.info("修改用户返回参数" + messageResult.getAsJSON());

        return messageResult.getAsJSON();
    }

    @RequestMapping(value = "/addUserRole", produces = "application/json; charset=utf-8")
    public @ResponseBody
    String addUserRole(HttpServletRequest request) throws Exception {
        String json = request.getParameter("json");

        log.info("用户添加角色请求参数" + json);

        MessageResult messageResult = new MessageResult();

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        UserRole userRole = mapper.readValue(json, UserRole.class);

        boolean flag = userService.addUserRole(userRole);

        if (flag)
            messageResult.setSuccessResult();
        else
            messageResult.setFailureResult();

        log.info("用户添加角色返回参数" + messageResult.getAsJSON());

        return messageResult.getAsJSON();
    }

    @RequestMapping(value = "/updateUserRole", produces = "application/json; charset=utf-8")
    public @ResponseBody
    String updateUserRole(HttpServletRequest request) throws Exception {
        String json = request.getParameter("json");

        log.info("修改用户角色请求参数" + json);

        MessageResult messageResult = new MessageResult();

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        UserRole userRole = mapper.readValue(json, UserRole.class);

        boolean flag = userService.updateUserRole(userRole);

        if (flag)
            messageResult.setSuccessResult();
        else
            messageResult.setFailureResult();

        log.info("修改用户角色返回参数" + messageResult.getAsJSON());

        return messageResult.getAsJSON();
    }

    @RequestMapping(value = "/queryUserRole", produces = "application/json; charset=utf-8")
    public @ResponseBody
    String queryUserRole(Integer id) throws Exception {
        log.info("点击用户角色请求参数" + id);

        MessageResult messageResult = new MessageResult();

        List<UserRole> list = userService.queryUserRole(id);

        if (list != null && list.size() > 0) {
            messageResult.setData(list);
            messageResult.setSuccessResult();
        } else {
            messageResult.setFailureResult();
        }

        return messageResult.getAsJSON();
    }

    @RequestMapping(value = "/queryRole", produces = "application/json; charset=utf-8")
    public @ResponseBody
    String queryRole() throws Exception {

        MessageResult messageResult = new MessageResult();

        List<Role> list = userService.queryRole();

        if (list != null && list.size() > 0) {
            messageResult.setData(list);
            messageResult.setSuccessResult();
        } else {
            messageResult.setFailureResult();
        }

        return messageResult.getAsJSON();
    }

    @RequestMapping(value = "/queryUser", produces = "application/json; charset=utf-8")
    public @ResponseBody
    String queryUser(@Valid @ModelAttribute("dto") QueryRoleDto dto) throws Exception {
        MessageResult messageResult = new MessageResult();

        log.info("用户查询请求参数" + dto);

        List<User> list = userService.queryUser(dto);
        if (list != null && list.size() > 0) {
            messageResult.setData(list);
            messageResult.setRows(userService.countUser(dto));
            messageResult.setSuccessResult();
        } else {
            messageResult.setFailureResult();
        }

        return messageResult.getAsJSON();
    }

    @RequestMapping(value = "/beforUpdateUser", produces = "applicaion/json; charset=utf-8")
    public @ResponseBody
    String beforUpdateUser(Integer id) throws Exception {
        log.info("修改用户前查询请求参数" + id);

        MessageResult messageResult = new MessageResult();

        User user = userService.beforUpdateUser(id);

        if (user != null) {
            messageResult.setData(user);
            messageResult.setSuccessResult();
        } else {
            messageResult.setFailureResult();
        }

        return messageResult.getAsJSON();
    }
}